package com.huidz.calendar.mainfragment;

import android.Manifest;
import android.app.ActivityOptions;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.Time;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarView;
import com.huidz.calendar.R;
import com.huidz.calendar.activity.ConstellationActivity;
import com.huidz.calendar.activity.FuWuTiaoKuanActivity;
import com.huidz.calendar.activity.GoodayActivity;
import com.huidz.calendar.activity.LunchActivity;
import com.huidz.calendar.activity.WebViewActivity;
import com.huidz.calendar.mainadapter.HomeAdapter;
import com.huidz.calendar.model.BWLSModel;
import com.huidz.calendar.model.CalendarModel;
import com.huidz.calendar.model.JsonBean;
import com.huidz.calendar.model.LochtingModel;
import com.huidz.calendar.model.TianQiModel;
import com.huidz.calendar.model.XingZuoModel;
import com.huidz.calendar.util.Apiutils;
import com.huidz.calendar.util.GetJsonDataUtil;
import com.huidz.calendar.util.LunarCalendar;
import com.huidz.calendar.util.MyDate;
import com.huidz.calendar.util.TianGanDizhiShengXiao;
import com.huidz.calendar.util.Url;
import com.huidz.calendar.util.ZodiacUtil;
import com.huidz.calendar.view.AdaptionSizeTextView;
import com.huidz.calendar.view.GregorianLunarCalendarView;
import com.huidz.calendar.view.NoScrollWebView;
import com.lljjcoder.style.citylist.CityListSelectActivity;
import com.lljjcoder.style.citylist.bean.CityInfoBean;
import com.wang.avi.AVLoadingIndicatorView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static android.app.Activity.RESULT_OK;

public class CalendarFragment extends Fragment implements View.OnClickListener, CalendarView.OnMonthChangeListener {
    //用于获取视图
    private View root;

    private ListView home_list;

    private ArrayList<String> new_list_view;
    /**************************************/
    public static CalendarView mCalendarView;
    private java.util.Calendar calendar;

    TextView titlecalendar, calendarnum, calendartype, calendarmsg, nicedaytext, festival, goodtext, lowtext, constellationmsg;
    ImageView hometitleadd;
    RelativeLayout room;

    /***气温***/
    TextView temperature, temperaturetext, quality_text, address, temperature_text_spacing, wind_speed;
    RelativeLayout quality;
    //明天
    TextView windlevel, state;
    RelativeLayout tomorrow_rela;
    //后天
    TextView windlevels, states;
    RelativeLayout tomorrows_rela;
    AdaptionSizeTextView tomorrows_spacing, tomorrow_spacing;
    public static String xingzuo;
    //星座运势
    private TextView changeconstellation, constellationtext, constellationtime;
    TextView luckynumtext, goldmantext, luckycolortext, constellations, changeconstellations;
    private TabLayout mytab;
    private RatingBar constellationtimeallratingBar, loveyunqiBar, workyunqiBar, licaiyunqiBar;
    private PopupWindow popupWindow, popupWindows;
    private ImageView changeimg;
    private LinearLayout tixing_line;
    public static String timestr = "";
    public static NoScrollWebView webViewNet;
    public static RelativeLayout xuanzedingwei;
    //判断是否有闰月
    //默认为false 表示没有
    //判断返回类型为int 大于0表示有闰月则返回1-12 返回等于0则表示没有闰月
    private Boolean is_lunar = false;

    private Boolean is_create = false;
    private AVLoadingIndicatorView loding_avis;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //定位权限
            if (ContextCompat.checkSelfPermission(getActivity(), locationPermission[0]) != PackageManager.PERMISSION_GRANTED) {
                // 如果没有授予该权限，就去提示用户请求
                requestPermissions(locationPermission, 300);
            }
        }
        root = inflater.inflate(R.layout.fragment_home, container, false);//初始加载
        if (Apiutils.isNetworkConnecteds)
            InitView(root);
        else {
            Apiutils.SetToast(getActivity(), "当前无网络连接");
        }
        is_create = true;
        return root;
    }

    private java.util.Calendar cal;


    /**
     * 初始加载视图
     */
    public void Init(View view) {
        home_list = view.findViewById(R.id.home_list);
        new_list_view = new ArrayList<>();
        HomeAdapter myAdapter = new HomeAdapter(new_list_view,
                getActivity());
        home_list.setAdapter(myAdapter);
    }

    public static int mway;
    public static String DATETIME = "";

    /**
     * 初始加载视图
     */
    public void InitView(View view) {
        loding_avis = view.findViewById(R.id.loding_avis);
        licaiyunqiBar = view.findViewById(R.id.licaiyunqiBar);
        workyunqiBar = view.findViewById(R.id.workyunqiBar);
        webViewNet = view.findViewById(R.id.webViewNet);
        webViewNet.getSettings().setBlockNetworkImage(false);
        webViewNet.setWebChromeClient(webChromeClient);
//        webViewNet.setWebViewClient(webViewClient);
        webViewNet.setVisibility(View.GONE);
        webViewNet.setWebViewClient(new MyWebViewClient());
//        {
//            @Override
//            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//            //使用WebView加载显示url
//            view.loadUrl(url);
//            //返回true
//            return true;
//        }
//        }
        room = view.findViewById(R.id.room);
        WebSettings webSettings = webViewNet.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webViewNet.loadUrl("http://cpu.baidu.com/1033/d2dfbec3?scid=56333");
        constellationtimeallratingBar = view.findViewById(R.id.constellationtimeallratingBar);
        loveyunqiBar = view.findViewById(R.id.loveyunqiBar);
        changeconstellations = view.findViewById(R.id.changeconstellations);
        changeconstellations.setOnClickListener(this);
        changeimg = view.findViewById(R.id.changeimg);
        constellations = view.findViewById(R.id.constellations);
        luckycolortext = view.findViewById(R.id.luckycolortext);
        goldmantext = view.findViewById(R.id.goldmantext);
        luckynumtext = view.findViewById(R.id.luckynumtext);
        constellationtime = view.findViewById(R.id.constellationtime);
        constellationtext = view.findViewById(R.id.constellationtext);
        tixing_line = view.findViewById(R.id.jishi);
        states = view.findViewById(R.id.states);
        state = view.findViewById(R.id.state);
        xuanzedingwei = view.findViewById(R.id.xuanzedingwei);
        xuanzedingwei.setOnClickListener(this);
        tomorrows_rela = view.findViewById(R.id.tomorrows_rela);
        tomorrows_rela.setOnClickListener(this);
        tomorrows_spacing = view.findViewById(R.id.tomorrows_spacing);
        windlevels = view.findViewById(R.id.windlevels);
        windlevel = view.findViewById(R.id.windlevel);
        tomorrow_rela = view.findViewById(R.id.tomorrow_rela);
        tomorrow_rela.setOnClickListener(this);
        wind_speed = view.findViewById(R.id.wind_speed);
        tomorrow_spacing = view.findViewById(R.id.tomorrow_spacing);
        temperature_text_spacing = view.findViewById(R.id.temperature_text_spacing);
        address = view.findViewById(R.id.address);
        quality = view.findViewById(R.id.quality);
        temperature = view.findViewById(R.id.temperature);
        quality_text = view.findViewById(R.id.quality_text);
        temperaturetext = view.findViewById(R.id.temperature_text);
        mCalendarView = view.findViewById(R.id.calendarView);
        titlecalendar = view.findViewById(R.id.titlecalendar);
        titlecalendar.setOnClickListener(this);
        calendarnum = view.findViewById(R.id.calendarnum);
        calendartype = view.findViewById(R.id.calendartype);
        calendarmsg = view.findViewById(R.id.calendarmsg);
        nicedaytext = view.findViewById(R.id.nicedaytext);
        nicedaytext.setOnClickListener(this);
        festival = view.findViewById(R.id.festival);
        goodtext = view.findViewById(R.id.goodtext);
        lowtext = view.findViewById(R.id.lowtext);
        changeconstellation = view.findViewById(R.id.changeconstellation);
        changeconstellation.setOnClickListener(this);
        hometitleadd = view.findViewById(R.id.hometitleadd);
        hometitleadd.setOnClickListener(this);
        constellationmsg = view.findViewById(R.id.constellationmsg);
        titlecalendar.setText(mCalendarView.getCurYear() + "年" + mCalendarView.getCurMonth() + "月");
        String s = LunarCalendar.getLunarString(mCalendarView.getCurYear(), mCalendarView.getCurMonth(), mCalendarView.getCurDay());
        java.util.Calendar selectedDate = java.util.Calendar.getInstance();
        Time t = new Time();
        t.setToNow(); // 取得系统时间。
        mway = selectedDate.get(java.util.Calendar.DAY_OF_WEEK);
        calendartype.setText(s + " 星期" + Apiutils.GetWeekday(mway));
        calendarnum.setText(mCalendarView.getCurDay() + "");
        timestr = titlecalendar.getText().toString();
        mCalendarView.setOnMonthChangeListener(this);
        String ss = LunarCalendar.getLunarString(CalendarFragment.mCalendarView.getCurYear(), CalendarFragment.mCalendarView.getCurMonth(), CalendarFragment.mCalendarView.getCurDay());
        String niceday = ss.substring(5, s.length());
        festival.setText(niceday);
        if (festival.getText().equals("")) {
            festival.setVisibility(View.GONE);
            room.setVisibility(View.GONE);
        } else {
            festival.setVisibility(View.VISIBLE);
            room.setVisibility(View.VISIBLE);
        }
        mytab = view.findViewById(R.id.mytab);
        mytab.addTab(mytab.newTab().setText("推荐"));
        mytab.addTab(mytab.newTab().setText("热门"));
        mytab.addTab(mytab.newTab().setText("娱乐"));
        mytab.addTab(mytab.newTab().setText("健康"));
        mytab.addTab(mytab.newTab().setText("笑话"));
        mytab.addTab(mytab.newTab().setText("本地"));
        mytab.addTab(mytab.newTab().setText("女人"));
        mytab.addTab(mytab.newTab().setText("汽车"));
        mytab.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                // 开启Fragment事务
                if (tab.getText().equals("推荐")) {
                    webViewNet.loadUrl("http://cpu.baidu.com/1033/d2dfbec3?scid=56333");
                }
                if (tab.getText().equals("热门")) {
                    webViewNet.loadUrl("https://cpu.baidu.com/1033/d2dfbec3?scid=56333");
                }
                if (tab.getText().equals("娱乐")) {
                    webViewNet.loadUrl("https://cpu.baidu.com/1001/d2dfbec3?scid=56331");
                }
                if (tab.getText().equals("健康")) {
                    webViewNet.loadUrl("https://cpu.baidu.com/1043/d2dfbec3?scid=57068");
                }
                if (tab.getText().equals("笑话")) {
                    webViewNet.loadUrl("https://cpu.baidu.com/1025/d2dfbec3?scid=57069");
                }
                if (tab.getText().equals("本地")) {
                    webViewNet.loadUrl("https://cpu.baidu.com/1080/d2dfbec3?scid=57074");
                }
                if (tab.getText().equals("女人")) {
                    webViewNet.loadUrl("https://cpu.baidu.com/1034/d2dfbec3?scid=57073");
                }
                if (tab.getText().equals("汽车")) {
                    webViewNet.loadUrl("https://cpu.baidu.com/1007/d2dfbec3?scid=57072");
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        mytab.setVisibility(View.GONE);
        if (!Url.USER_TOKEN.equals("")) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date gettime = new Date(System.currentTimeMillis());
            time_s = simpleDateFormat.format(gettime);
            gettianqi();
        }
        /**************以下全部都需要***************/
        initJsonData();
        if (mCalendarView.getCurMonth() > 9 && mCalendarView.getCurDay() > 9) {
            DATETIME = mCalendarView.getCurYear() + "-" + mCalendarView.getCurMonth() + "-" + mCalendarView.getCurDay();
            SelectCode(mCalendarView.getCurYear() + "-" + mCalendarView.getCurMonth() + "-" + mCalendarView.getCurDay());
            MyDate.initGanZhi(mCalendarView.getCurYear(), mCalendarView.getCurMonth(), mCalendarView.getCurDay());
            xingzuo = ZodiacUtil.date2Constellation(mCalendarView.getCurYear() + "-" + mCalendarView.getCurMonth() + "-" + mCalendarView.getCurDay());
            time_s = mCalendarView.getCurYear() + "-" + mCalendarView.getCurMonth() + "-" + mCalendarView.getCurDay();
            if (!Url.USER_TOKEN.equals(""))
                gettianqi();
        } else if (mCalendarView.getCurMonth() > 9 && mCalendarView.getCurDay() <= 9) {
            DATETIME = mCalendarView.getCurYear() + "-" + mCalendarView.getCurMonth() + "-" + ("0" + mCalendarView.getCurDay());
            SelectCode(mCalendarView.getCurYear() + "-" + mCalendarView.getCurMonth() + "-" + ("0" + mCalendarView.getCurDay()));
            MyDate.initGanZhi(mCalendarView.getCurYear(), mCalendarView.getCurMonth(), Integer.parseInt("0" + mCalendarView.getCurDay()));
            xingzuo = ZodiacUtil.date2Constellation(mCalendarView.getCurYear() + "-" + mCalendarView.getCurMonth() + "-" + ("0" + mCalendarView.getCurDay()));
            time_s = mCalendarView.getCurYear() + "-" + mCalendarView.getCurMonth() + "-" + ("0" + mCalendarView.getCurDay());
            if (!Url.USER_TOKEN.equals(""))
                gettianqi();
        } else if (mCalendarView.getCurMonth() <= 9 && mCalendarView.getCurDay() <= 9) {
            DATETIME = mCalendarView.getCurYear() + "-" + ("0" + mCalendarView.getCurMonth()) + "-" + ("0" + mCalendarView.getCurDay());
            SelectCode(mCalendarView.getCurYear() + "-" + ("0" + mCalendarView.getCurMonth()) + "-" + ("0" + mCalendarView.getCurDay()));
            MyDate.initGanZhi(mCalendarView.getCurYear(), Integer.parseInt("0" + mCalendarView.getCurMonth()), Integer.parseInt("0" + mCalendarView.getCurDay()));
            xingzuo = ZodiacUtil.date2Constellation(mCalendarView.getCurYear() + "-" + ("0" + mCalendarView.getCurMonth()) + "-" + ("0" + mCalendarView.getCurDay()));
            time_s = mCalendarView.getCurYear() + "-" + ("0" + mCalendarView.getCurMonth()) + "-" + ("0" + mCalendarView.getCurDay());
            if (!Url.USER_TOKEN.equals(""))
                gettianqi();
        } else {
            DATETIME = mCalendarView.getCurYear() + "-" + ("0" + mCalendarView.getCurMonth()) + "-" + mCalendarView.getCurDay();
            SelectCode(mCalendarView.getCurYear() + "-" + ("0" + mCalendarView.getCurMonth()) + "-" + mCalendarView.getCurDay());
            MyDate.initGanZhi(mCalendarView.getCurYear(), Integer.parseInt("0" + mCalendarView.getCurMonth()), mCalendarView.getCurDay());
            xingzuo = ZodiacUtil.date2Constellation(mCalendarView.getCurYear() + "-" + ("0" + mCalendarView.getCurMonth()) + "-" + mCalendarView.getCurDay());
            time_s = mCalendarView.getCurYear() + "-" + ("0" + mCalendarView.getCurMonth()) + "-" + mCalendarView.getCurDay();
            if (!Url.USER_TOKEN.equals(""))
                gettianqi();
        }
        calendarmsg.setText(Apiutils.Niantg + "年 " + Apiutils.Yuetg + "月 " + Apiutils.Ritg + "日 「属" + TianGanDizhiShengXiao.getAnimalYearName(mCalendarView.getCurYear()) + "」");
        SelectYiJi(gz + "", jx + "");
//        mCalendarView.setOnCalendarSelectListener(new CalendarView.OnCalendarSelectListener() {
//            @Override
//            public void onCalendarOutOfRange(Calendar calendar) {
//
//            }
//
//            @Override
//            public void onCalendarSelect(Calendar calendar, boolean isClick) {
//
//            }
//        });
        mCalendarView.setOnDateSelectedListener(new CalendarView.OnDateSelectedListener() {
            @Override
            public void onDateSelected(Calendar calendar, boolean isClick) {
                if (is_create) {
                    String s = null;
                    int week = 0;
                    week = calendar.getWeek() + 1;
                    if (calendar.getMonth() > 9 && calendar.getDay() > 9) {
                        SelectCode(calendar.getYear() + "-" + calendar.getMonth() + "-" + calendar.getDay());
                        MyDate.initGanZhi(calendar.getYear(), calendar.getMonth(), calendar.getDay());
                        s = LunarCalendar.getLunarString(calendar.getYear(), calendar.getMonth(), calendar.getDay());
                        AlmanacFragment.home(calendar.getYear() + "-" + calendar.getMonth() + "-" + calendar.getDay(), calendar.getMonth(), calendar.getDay(), s, Apiutils.Niantg + "年 " + Apiutils.Yuetg + "月 " + Apiutils.Ritg + "日 「属" + TianGanDizhiShengXiao.getAnimalYearName(calendar.getYear()) + "」", s + " 星期" + Apiutils.GetWeekday(week), calendar.getYear() + "年" + calendar.getMonth() + "月", true);
                        calendarnum.setText("" + calendar.getDay());
                        time_s = calendar.getYear() + "-" + calendar.getMonth() + "-" + calendar.getDay();
                    } else if (calendar.getMonth() > 9 && calendar.getDay() <= 9) {
                        SelectCode(calendar.getYear() + "-" + calendar.getMonth() + "-" + ("0" + calendar.getDay()));
                        MyDate.initGanZhi(calendar.getYear(), calendar.getMonth(), Integer.parseInt("0" + calendar.getDay()));
                        s = LunarCalendar.getLunarString(calendar.getYear(), calendar.getMonth(), Integer.parseInt("0" + calendar.getDay()));
                        AlmanacFragment.home(calendar.getYear() + "-" + calendar.getMonth() + "-" + ("0" + calendar.getDay()), calendar.getMonth(), Integer.parseInt("0" + calendar.getDay()), s, Apiutils.Niantg + "年 " + Apiutils.Yuetg + "月 " + Apiutils.Ritg + "日 「属" + TianGanDizhiShengXiao.getAnimalYearName(calendar.getYear()) + "」", s + " 星期" + Apiutils.GetWeekday(week), calendar.getYear() + "年" + calendar.getMonth() + "月", true);
                        calendarnum.setText("0" + calendar.getDay());
                        time_s = calendar.getYear() + "-" + calendar.getMonth() + "-" + ("0" + calendar.getDay());
                    } else if (calendar.getMonth() <= 9 && calendar.getDay() <= 9) {
                        SelectCode(calendar.getYear() + "-" + ("0" + calendar.getMonth()) + "-" + ("0" + calendar.getDay()));
                        MyDate.initGanZhi(calendar.getYear(), Integer.parseInt("0" + calendar.getMonth()), Integer.parseInt("0" + calendar.getDay()));
                        s = LunarCalendar.getLunarString(calendar.getYear(), Integer.parseInt("0" + calendar.getMonth()), Integer.parseInt("0" + calendar.getDay()));
                        AlmanacFragment.home(calendar.getYear() + "-" + ("0" + calendar.getMonth()) + "-" + ("0" + calendar.getDay()), calendar.getMonth(), Integer.parseInt("0" + calendar.getDay()), s, Apiutils.Niantg + "年 " + Apiutils.Yuetg + "月 " + Apiutils.Ritg + "日 「属" + TianGanDizhiShengXiao.getAnimalYearName(calendar.getYear()) + "」", s + " 星期" + Apiutils.GetWeekday(week), calendar.getYear() + "年" + calendar.getMonth() + "月", true);
                        calendarnum.setText("0" + calendar.getDay());
                        time_s = calendar.getYear() + "-" + ("0" + calendar.getMonth()) + "-" + ("0" + calendar.getDay());
                    } else {
                        SelectCode(calendar.getYear() + "-" + ("0" + calendar.getMonth()) + "-" + calendar.getDay());
                        MyDate.initGanZhi(calendar.getYear(), Integer.parseInt("0" + calendar.getMonth()), calendar.getDay());
                        s = LunarCalendar.getLunarString(calendar.getYear(), Integer.parseInt("0" + calendar.getMonth()), calendar.getDay());
                        AlmanacFragment.home(calendar.getYear() + "-" + ("0" + calendar.getMonth()) + "-" + calendar.getDay(), calendar.getMonth(), calendar.getDay(), s, Apiutils.Niantg + "年 " + Apiutils.Yuetg + "月 " + Apiutils.Ritg + "日 「属" + TianGanDizhiShengXiao.getAnimalYearName(calendar.getYear()) + "」", s + " 星期" + Apiutils.GetWeekday(week), calendar.getYear() + "年" + calendar.getMonth() + "月", true);
                        calendarnum.setText("" + calendar.getDay());
                        time_s = calendar.getYear() + "-" + ("0" + calendar.getMonth()) + "-" + calendar.getDay();
                    }
                    if (!Url.USER_TOKEN.equals(""))
                        gettianqi();
                    SelectYiJi(gz + "", jx + "");
                    String niceday = s.substring(5, s.length());
                    festival.setText(niceday);
                    calendartype.setText(s + " 星期" + Apiutils.GetWeekday(week));
                    calendarmsg.setText(Apiutils.Niantg + "年 " + Apiutils.Yuetg + "月 " + Apiutils.Ritg + "日 「属" + TianGanDizhiShengXiao.getAnimalYearName(calendar.getYear()) + "」");
                    if (festival.getText().equals("")) {
                        festival.setVisibility(View.GONE);
                        room.setVisibility(View.GONE);
                    } else {
                        festival.setVisibility(View.VISIBLE);
                        room.setVisibility(View.VISIBLE);
                    }
                }
            }
        });
        okHttp_postFromParameters(mCalendarView.getCurYear() + "");
        selectxingzuo(xingzuo);
        get(xingzuo);
        /******************************************************/
        gettianqis(Url.latitude, Url.longitude);
        if (Url.QIDONGNUM.equals("")) {
            LayoutInflater inflater = LayoutInflater.from(getActivity());
            View layout = inflater.inflate(R.layout.popupwindow_yinsiquanxian, null);
            two = layout.findViewById(R.id.two);
            two.setOnClickListener(this);
            four = layout.findViewById(R.id.four);
            four.setOnClickListener(this);
            nit = layout.findViewById(R.id.nit);
            nit.setOnClickListener(this);
            shis = layout.findViewById(R.id.shi);
            shis.setOnClickListener(this);
            new AlertDialog.Builder(getActivity())
                    .setCancelable(false)
                    .setTitle("用户协议和隐私政策")
                    .setView(layout)
                    .setPositiveButton("是", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    })
                    .setNegativeButton("否", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            getActivity().onBackPressed();
                        }
                    })
                    .show();
        }
    }

    private WebChromeClient webChromeClient = new WebChromeClient() {
        //不支持js的alert弹窗，需要自己监听然后通过dialog弹窗
        @Override
        public boolean onJsAlert(WebView webView, String url, String message, JsResult result) {
            android.app.AlertDialog.Builder localBuilder = new android.app.AlertDialog.Builder(webView.getContext());
            localBuilder.setMessage(message).setPositiveButton("确定", null);
            localBuilder.setCancelable(false);
            localBuilder.create().show();
            result.confirm();
            return true;
        }

        //获取网页标题
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
        }

        //加载进度回调
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress >= 100) {
                loding_avis.setVisibility(View.GONE);
                webViewNet.setVisibility(View.VISIBLE);
                iwebview++;
                webfinished = true;
            }
        }
    };

//    private WebViewClient webViewClient = new WebViewClient() {
//        @Override
//        public void onPageFinished(WebView view, String url) {//页面加载完成
//        }
//
//        @Override
//        public void onPageStarted(WebView view, String url, Bitmap favicon) {//页面开始加载
//        }
//
//        @Override
//        public boolean shouldOverrideUrlLoading(WebView view, String url) {
//            if (url.equals("http://www.google.com/")) {
//                Toast.makeText(getActivity(), "国内不能访问google,拦截该url", Toast.LENGTH_LONG).show();
//                return true;//表示我已经处理过了
//            }
//            return super.shouldOverrideUrlLoading(view, url);
//        }
//
//    };


    private TextView two, four, nit, shis;
    private boolean login_ = true;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.two:
                Intent yhxy = new Intent(getActivity(), FuWuTiaoKuanActivity.class);
                yhxy.putExtra("url", "http://web.xuekaixin.cn/article/show/id/10000.html");
                yhxy.putExtra("title", "用户协议");
                startActivity(yhxy);
                break;
            case R.id.four:
                Intent yszc = new Intent(getActivity(), FuWuTiaoKuanActivity.class);
                yszc.putExtra("url", "http://web.xuekaixin.cn/article/show/id/10001.html");
                yszc.putExtra("title", "隐私政策");
                startActivity(yszc);
                break;
            case R.id.nit:
                Intent yhxy1 = new Intent(getActivity(), FuWuTiaoKuanActivity.class);
                yhxy1.putExtra("url", "http://web.xuekaixin.cn/article/show/id/10000.html");
                yhxy1.putExtra("title", "用户协议");
                startActivity(yhxy1);
                break;
            case R.id.shi:
                Intent yszc1 = new Intent(getActivity(), FuWuTiaoKuanActivity.class);
                yszc1.putExtra("url", "http://web.xuekaixin.cn/article/show/id/10001.html");
                yszc1.putExtra("title", "隐私政策");
                startActivity(yszc1);
                break;
            case R.id.xuanzedingwei:
                if (isLoaded)
                    selectcity();
                else {
                    Apiutils.SetToast(getActivity(), "城市列表初始化中");
                }
                break;
            case R.id.hometitleadd:

                break;
            case R.id.tomorrow_rela:
                break;
            case R.id.tomorrows_rela:

                break;
            case R.id.changeconstellation:
                windows(getActivity());
                break;
            case R.id.changeconstellations:
                Intent toconstellationmsg = new Intent(getActivity(), ConstellationActivity.class);
                startActivity(toconstellationmsg, ActivityOptions.makeSceneTransitionAnimation(getActivity()).toBundle());
                break;
            case R.id.titlecalendar:
                is_lunar = false;
                getcalendar = 0;
                window(getActivity());
                break;
            case R.id.nicedaytext:
                Intent togooday = new Intent(getActivity(), GoodayActivity.class);
                startActivity(togooday, ActivityOptions.makeSceneTransitionAnimation(getActivity()).toBundle());
                break;
        }
    }


    public void initdate() throws ParseException {
        List<Calendar> map1 = new ArrayList<>();
        for (int calendar = 0; calendar < arrayList.size(); calendar++) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//小写的mm表示的是分钟
            Date date = sdf.parse(userm.getData().get(calendar).getDate());
            Date dates = new Date(date.getTime());
            int y = Integer.parseInt(sdf.format(dates).substring(0, 4));
            int m = Integer.parseInt(sdf.format(dates).substring(5, 7));
            int d = Integer.parseInt(sdf.format(dates).substring(8, 10));
            if (arrayList.get(calendar).getStatus().equals("1"))
                map1.add(Apiutils.getSchemeCalendar(y, m, d, 0xFFffffff, "休"));//0xFF13acf0
            else
                map1.add(Apiutils.getSchemeCalendar(y, m, d, 0xFF13acf0, "班"));
        }
        mCalendarView.setSchemeDate(map1);
    }

    java.util.Calendar calendars;
    String getluanrdate;
    int getluanrdateINT;

    @Override
    public void onMonthChange(int year, int month) {
        titlecalendar.setText(year + "年" + month + "月");
    }

    GregorianLunarCalendarView mGLCView;
    private RelativeLayout Gregorian, getLunar;
    private TextView Gregoriantext, getLunartext;
    //拥有判断是公历还是农历
    private int getcalendar = 0;//0为公历,默认情况下选择是公历
    private TextView title_text, get_title_text;
    int y;
    int m;
    int d;
    String[] locationPermission = {Manifest.permission.ACCESS_FINE_LOCATION};

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 300:
                if (ContextCompat.checkSelfPermission(getActivity(), locationPermission[0]) != PackageManager.PERMISSION_GRANTED) {
                    // 如果没有授予该权限，就去提示用户请求
                    Toast.makeText(getActivity(), "定位服务被禁止，为保证软件正常运行。请手动开起！", Toast.LENGTH_LONG).show();
                } else {
                    LunchActivity.locationManager.requestLocationUpdates("network", 0, 0, LunchActivity.myLocationListener);

                    new Handler().postDelayed(new Runnable() {
                        public void run() {
                            gettianqis(Url.latitude, Url.longitude);
                        }
                    }, 1000);
                }
                break;
            default:
                break;
        }
    }

    public void window(Context context) {
        View popupwindowview = LayoutInflater.from(context).inflate(
                R.layout.seleced_calendar, null);
        mGLCView = popupwindowview.findViewById(R.id.calendar_view);
        //采用GregorianLunarCalendarView.CalendarData内部类来存储当前日期，使用getCalendarData()函数获取选中date数据
        GregorianLunarCalendarView.CalendarData calendarData = mGLCView.getCalendarData();
        //进一步获取日期
        calendar = calendarData.getCalendar();
        mGLCView.init();
        Gregorian = popupwindowview.findViewById(R.id.Gregorian);
        getLunar = popupwindowview.findViewById(R.id.getLunar);
        Gregoriantext = popupwindowview.findViewById(R.id.Gregoriantext);
        getLunartext = popupwindowview.findViewById(R.id.getLunartext);
        get_title_text = popupwindowview.findViewById(R.id.get_title_text);
        title_text = popupwindowview.findViewById(R.id.title_text);
        title_text.setText(R.string.msgtext);
        Gregorian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                title_text.setText(R.string.msgtext);
                getcalendar = 0;
                Gregorian.setBackgroundDrawable(getResources().getDrawable(R.drawable.rili_select_rela));
                getLunar.setBackgroundDrawable(getResources().getDrawable(R.color.colorwhite50));
                Gregoriantext.setTextColor(getResources().getColor(R.color.colorwhite));
                getLunartext.setTextColor(getResources().getColor(R.color.title_color));
                get_title_text.setText("");
            }
        });
        getLunar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                title_text.setText(R.string.msgtext1);
                getcalendar = 1;
                Gregorian.setBackgroundDrawable(getResources().getDrawable(R.color.colorwhite50));
                getLunar.setBackgroundDrawable(getResources().getDrawable(R.drawable.rili_select_rela));
                Gregoriantext.setTextColor(getResources().getColor(R.color.title_color));
                getLunartext.setTextColor(getResources().getColor(R.color.colorwhite));
                get_title_text.setText("");
            }
        });
        RelativeLayout close_rela = popupwindowview.findViewById(R.id.close_rela);
        close_rela.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
            }
        });
        mGLCView.setOnDateChangedListener(new GregorianLunarCalendarView.OnDateChangedListener() {
            @Override
            public void onDateChanged(GregorianLunarCalendarView.CalendarData calendarData) {
                java.util.Calendar calendars = calendarData.getCalendar();
                String text_msg;
                if (getcalendar == 0)//选择的是公历{
                {
                    y = calendars.get(java.util.Calendar.YEAR);
                    m = calendars.get(java.util.Calendar.MONTH) + 1;
                    d = calendars.get(java.util.Calendar.DAY_OF_MONTH);
                    text_msg = "公历";
                    get_title_text.setText("当前对应的" + text_msg + ":" + y + "年" + m + "月" + d + "日");
                } else {
                    getluanrdate = LunarCalendar.getLunarDateINT(calendars.get(java.util.Calendar.YEAR), (calendars.get(java.util.Calendar.MONTH) + 1), calendars.get(java.util.Calendar.DAY_OF_MONTH)) + "";
                    String s = LunarCalendar.getLunarString(calendars.get(java.util.Calendar.YEAR), (calendars.get(java.util.Calendar.MONTH) + 1), calendars.get(java.util.Calendar.DAY_OF_MONTH));
                    y = Integer.parseInt(getluanrdate.substring(0, 4));
                    m = Integer.parseInt(getluanrdate.substring(4, 6));
                    d = Integer.parseInt(getluanrdate.substring(6, 8));
                    text_msg = s;
                    get_title_text.setText("当前对应的农历是" + text_msg + "," + y + "年" + m + "月" + d + "日");
                }
            }
        });
        TextView is_today = popupwindowview.findViewById(R.id.is_today);
        is_today.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mGLCView.init();
            }
        });
        RelativeLayout ok_rela = popupwindowview.findViewById(R.id.ok_rela);
        ok_rela.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                GregorianLunarCalendarView.CalendarData calendarData = mGLCView.getCalendarData();
                calendars = calendarData.getCalendar();
                int leapDays = LunarCalendar.leapMonth(calendars.get(java.util.Calendar.YEAR));
                if (leapDays > 0)
                    is_lunar = true;
                else
                    is_lunar = false;
                if (getcalendar == 0)//选择的是公历{
                {
                    int y = calendars.get(java.util.Calendar.YEAR);
                    int m = calendars.get(java.util.Calendar.MONTH) + 1;
                    int d = calendars.get(java.util.Calendar.DAY_OF_MONTH);
                    popupWindow.dismiss();
                    mCalendarView.scrollToCalendar(y, m, d);
                } else {
                    getluanrdate = LunarCalendar.getLunarDateINT(calendars.get(java.util.Calendar.YEAR), (calendars.get(java.util.Calendar.MONTH) + 1), calendars.get(java.util.Calendar.DAY_OF_MONTH)) + "";
                    int y = Integer.parseInt(getluanrdate.substring(0, 4));
                    int m = Integer.parseInt(getluanrdate.substring(4, 6));
                    int d = Integer.parseInt(getluanrdate.substring(6, 8));
                    popupWindow.dismiss();
                    mCalendarView.scrollToCalendar(y, m, d);
                }
            }
        });
        popupWindow = new
                PopupWindow(popupwindowview, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
        // 外部点击事件
        popupWindow.setTouchable(true);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // TODO Auto-generated method stub
                WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
                lp.alpha = 1f;
                getActivity().getWindow().setAttributes(lp);
            }
        });
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = 0.4f;
        getActivity().
                getWindow().
                setAttributes(lp);
        popupWindow.showAtLocation(mCalendarView, Gravity.CENTER, 10, 10);
    }


    private LinearLayout shuiping, shuangyu, baiyang, shuangzi, jinniu, juxie, shizi, chunv, tiancheng, tianxie, sheshou, mojie;

    public void windows(Context context) {
        View popupwindowview = LayoutInflater.from(context).inflate(
                R.layout.seleced_constellation, null);
        shuiping = popupwindowview.findViewById(R.id.shuiping);
        shuangyu = popupwindowview.findViewById(R.id.shuangyu);
        baiyang = popupwindowview.findViewById(R.id.baiyang);
        shuangzi = popupwindowview.findViewById(R.id.shuangzi);
        jinniu = popupwindowview.findViewById(R.id.jinniu);
        juxie = popupwindowview.findViewById(R.id.juxie);
        shizi = popupwindowview.findViewById(R.id.shizi);
        chunv = popupwindowview.findViewById(R.id.chunv);
        tiancheng = popupwindowview.findViewById(R.id.tiancheng);
        tianxie = popupwindowview.findViewById(R.id.tianxie);
        sheshou = popupwindowview.findViewById(R.id.sheshou);
        mojie = popupwindowview.findViewById(R.id.mojie);
        popuponclick();
        popupWindows = new
                PopupWindow(popupwindowview, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
        // 外部点击事件
        popupWindows.setTouchable(true);
        popupWindows.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // TODO Auto-generated method stub
                WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
                lp.alpha = 1f;
                getActivity().getWindow().setAttributes(lp);
            }
        });
        popupWindows.setFocusable(true);
        popupWindows.setOutsideTouchable(true);
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = 0.4f;
        getActivity().
                getWindow().
                setAttributes(lp);
        popupWindows.showAtLocation(changeconstellation, Gravity.CENTER, 10, 10);
    }

    //popupwindow里的点击事件
    public void popuponclick() {
        shuiping.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                get("水瓶座");
                xingzuo = "水瓶座";
                changeimg.setBackgroundResource(R.mipmap.spz);
                constellationtext.setText(R.string.shuipingzuo);
                constellationtime.setText(R.string.shuipingtime1);
                popupWindows.dismiss();
            }
        });
        shuangyu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                get("双鱼座");
                xingzuo = "双鱼座";
                changeimg.setBackgroundResource(R.mipmap.syz);
                constellationtext.setText(R.string.shuangyuzuo);
                constellationtime.setText(R.string.shuangyutime1);
                popupWindows.dismiss();
            }
        });
        baiyang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                get("白羊座");
                xingzuo = "白羊座";
                changeimg.setBackgroundResource(R.mipmap.byz);
                constellationtext.setText(R.string.baiyangzuo);
                constellationtime.setText(R.string.baiyangtime1);
                popupWindows.dismiss();
            }
        });
        shuangzi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                get("双子座");
                xingzuo = "双子座";
                changeimg.setBackgroundResource(R.mipmap.sziz);
                constellationtext.setText(R.string.shuangzizuo);
                constellationtime.setText(R.string.shuangzitime1);
                popupWindows.dismiss();
            }
        });
        jinniu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                get("金牛座");
                xingzuo = "金牛座";
                changeimg.setBackgroundResource(R.mipmap.jnz);
                constellationtext.setText(R.string.jinniuzuo);
                constellationtime.setText(R.string.jinniutime1);
                popupWindows.dismiss();
            }
        });
        juxie.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                get("巨蟹座");
                xingzuo = "巨蟹座";
                changeimg.setBackgroundResource(R.mipmap.jxz);
                constellationtext.setText(R.string.juxiezuo);
                constellationtime.setText(R.string.juxietime1);
                popupWindows.dismiss();
            }
        });
        shizi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                get("双子座");
                xingzuo = "双子座";
                changeimg.setBackgroundResource(R.mipmap.szz);
                constellationtext.setText(R.string.shizizuo);
                constellationtime.setText(R.string.shizitime1);
                popupWindows.dismiss();
            }
        });
        chunv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                get("处女座");
                xingzuo = "处女座";
                changeimg.setBackgroundResource(R.mipmap.cnz);
                constellationtext.setText(R.string.chunvzuo);
                constellationtime.setText(R.string.chunvtime1);
                popupWindows.dismiss();
            }
        });
        tiancheng.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                get("天秤座");
                xingzuo = "天秤座";
                changeimg.setBackgroundResource(R.mipmap.tcz);
                constellationtext.setText(R.string.tianchengzuo);
                constellationtime.setText(R.string.tianchengtime1);
                popupWindows.dismiss();
            }
        });
        tianxie.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                get("天蝎座");
                xingzuo = "天蝎座";
                changeimg.setBackgroundResource(R.mipmap.txz);
                constellationtime.setText(R.string.tianxietime1);
                constellationtext.setText(R.string.tianxiezuo);
                popupWindows.dismiss();
            }
        });
        sheshou.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                get("射手座");
                xingzuo = "射手座";
                changeimg.setBackgroundResource(R.mipmap.ssz);
                constellationtext.setText(R.string.sheshouzuo);
                constellationtime.setText(R.string.sheshoutime1);
                popupWindows.dismiss();
            }
        });
        mojie.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                get("摩羯座");
                xingzuo = "摩羯座";
                changeimg.setBackgroundResource(R.mipmap.mjz);
                constellationtext.setText(R.string.mojiezuo);
                constellationtime.setText(R.string.mojietime1);
                popupWindows.dismiss();
            }
        });
    }

    public int iwebview = 0;

    // 监听 所有点击的链接，如果拦截到我们需要的，就跳转到相对应的页面。
    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            if (url != null && webfinished & iwebview >= 1) {
                view.stopLoading();
                Intent intent = new Intent(getActivity(), WebViewActivity.class);
                intent.putExtra("url", url);
                startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(getActivity()).toBundle());
                return true;
            }


            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            view.getSettings().setJavaScriptEnabled(true);
            super.onPageFinished(view, url);
        }
    }

    private boolean webfinished = false;
    private SQLiteDatabase database;
    private String yi, ji;

    /**
     * 获取宜忌的方法
     *
     * @param gz 条件查询值，传入时间
     */
    public void SelectYiJi(String gz, String jx) {
        File file = new File(getContext().getFilesDir(), "saa.db");
        database = SQLiteDatabase.openDatabase(file.getAbsolutePath(), null, SQLiteDatabase.OPEN_READONLY);
        Cursor mCursor = database.query("YJData", null, "jx=? and gz=?", new String[]{jx, gz}, null,
                null, null);
        while (mCursor.moveToNext()) {
            yi = mCursor.getString(3);
            goodtext.setText(yi);
            if(goodtext.getText().equals(""))
                goodtext.setText("无");
            ji = mCursor.getString(2);
            lowtext.setText(ji);
            if(lowtext.getText().equals(""))
                lowtext.setText("无");
        }
    }

    private int jx, gz;

    /**
     * 获取时间的code
     *
     * @param _Date 传入时间
     */
    public void SelectCode(String _Date) {
        File file = new File(getContext().getFilesDir(), "saa.db");
        database = SQLiteDatabase.openDatabase(file.getAbsolutePath(), null, SQLiteDatabase.OPEN_READONLY);
        Cursor mCursor = database.query("IndexTable", null, "_Date=?", new String[]{_Date}, null,
                null, null);
        while (mCursor.moveToNext()) {
            jx = Integer.parseInt(mCursor.getString(1));
            gz = Integer.parseInt(mCursor.getString(2));
        }
    }

    private ArrayList<CalendarModel.data> arrayList = new ArrayList<>();

    public void okHttp_postFromParameters(final String year) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    RequestBody formBody = new FormBody.Builder().add("year", year)
                            .build();
                    Request request = new Request.Builder().url(Url.JIARI).post(formBody).build();
                    okhttp3.Response response = okHttpClient.newCall(request).execute();
                    String msg = response.body().string();
                    Message message = new Message();
                    message.obj = msg;
                    gethot.sendMessage(message);
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CityListSelectActivity.CITY_SELECT_RESULT_FRAG) {
            if (resultCode == RESULT_OK) {
                Bundle bundle = data.getExtras();
                CityInfoBean cityInfoBean = (CityInfoBean) bundle.getParcelable("cityinfo");
                if (cityInfoBean != null) {
                    Apiutils.getGeoPointBystr(getActivity(), cityInfoBean.getName());
                    gettianqis(Url.latitude, Url.longitude);
                }
            }

        }
    }

    public CalendarModel userm;
    public Handler gethot = new Handler() {
        public void handleMessage(Message msg) {
            String msgs = null;
            try {
                JSONObject success_Object = null;
                if (msg.obj != null) {
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    msgs = success_Object.getString("msg");
                    if (code.equals("1")) {
                        Gson gson = new Gson();
                        userm = gson.fromJson(msg.obj.toString(),
                                CalendarModel.class);
                        arrayList.addAll(userm.getData());
                        initdate();
                    } else
                        Apiutils.SetToast(getActivity(), msgs + "");
                }
            } catch (
                    Exception e) {
                e.printStackTrace();
            }
        }
    };

    public Handler gethots = new Handler() {
        public void handleMessage(Message msg) {
            String msgs = null;
            try {
                JSONObject success_Object = null;
                if (msg.obj != null) {
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    msgs = success_Object.getString("msg");
                    if (code.equals("1")) {
                        Gson gson = new Gson();
                        xingZuoModel = gson.fromJson(msg.obj.toString(),
                                XingZuoModel.class);
                        luckycolortext.setText(xingZuoModel.getData().getContent().getToday().getFonums().get(6).getDes());
                        goldmantext.setText(xingZuoModel.getData().getContent().getToday().getFonums().get(7).getDes());
                        luckynumtext.setText(xingZuoModel.getData().getContent().getToday().getFonums().get(5).getDes());
                        float rating = (Float.parseFloat(xingZuoModel.getData().getContent().getToday().getFonums().get(0).getDes()) / 2) / 10;
                        float loverating = (Float.parseFloat(xingZuoModel.getData().getContent().getToday().getFonums().get(2).getDes()) / 2) / 10;
                        float workrating = (Float.parseFloat(xingZuoModel.getData().getContent().getToday().getFonums().get(1).getDes()) / 2) / 10;
                        float moneyrating = (Float.parseFloat(xingZuoModel.getData().getContent().getToday().getFonums().get(3).getDes()) / 2) / 10;
                        constellationtimeallratingBar.setRating(rating);
                        loveyunqiBar.setRating(loverating);
                        workyunqiBar.setRating(workrating);
                        licaiyunqiBar.setRating(moneyrating);
                        constellationmsg.setText(xingZuoModel.getData().getContent().getToday().getFodeses().get(0).getDes());
                        gettianqi(Url.address_code);
                    }
                }
            } catch (
                    Exception e) {
                e.printStackTrace();
            }
        }
    };

    public static XingZuoModel xingZuoModel;

    public void get(String view) {
        OkHttpClient client = new OkHttpClient();
        //构造Request对象
        //采用建造者模式，链式调用指明进行Get请求,传入Get的请求地址
        Request request = new Request.Builder().get().url(Url.XINGZUO + "?constellation=" + view).build();
        Call call = client.newCall(request);
        //异步调用并设置回调函数
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, final Response response) {
                try {
                    final String responseStr;
                    responseStr = response.body().string();
                    Message message = new Message();
                    message.obj = responseStr;
                    gethots.sendMessage(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void selectxingzuo(String name) {
        switch (name) {
            case "水瓶座":
                changeimg.setBackgroundResource(R.mipmap.spz);
                constellationtext.setText(R.string.shuipingzuo);
                constellationtime.setText(R.string.shuipingtime1);
                break;
            case "双鱼座":
                changeimg.setBackgroundResource(R.mipmap.syz);
                constellationtext.setText(R.string.shuangyuzuo);
                constellationtime.setText(R.string.shuangyutime1);
                break;
            case "白羊座":
                changeimg.setBackgroundResource(R.mipmap.byz);
                constellationtext.setText(R.string.baiyangzuo);
                constellationtime.setText(R.string.baiyangtime1);
                break;
            case "双子座":
                changeimg.setBackgroundResource(R.mipmap.sziz);
                constellationtext.setText(R.string.shuangzizuo);
                constellationtime.setText(R.string.shuangzitime1);
                break;
            case "金牛座":
                changeimg.setBackgroundResource(R.mipmap.jnz);
                constellationtext.setText(R.string.jinniuzuo);
                constellationtime.setText(R.string.jinniutime1);
                break;
            case "巨蟹座":
                changeimg.setBackgroundResource(R.mipmap.jxz);
                constellationtext.setText(R.string.juxiezuo);
                constellationtime.setText(R.string.juxietime1);
                break;
            case "狮子座":
                changeimg.setBackgroundResource(R.mipmap.szz);
                constellationtext.setText(R.string.shizizuo);
                constellationtime.setText(R.string.shizitime1);
                break;
            case "处女座":
                changeimg.setBackgroundResource(R.mipmap.cnz);
                constellationtext.setText(R.string.chunvzuo);
                constellationtime.setText(R.string.chunvtime1);
                break;
            case "天秤座":
                changeimg.setBackgroundResource(R.mipmap.tcz);
                constellationtext.setText(R.string.tianchengzuo);
                constellationtime.setText(R.string.tianchengtime1);
                break;
            case "天蝎座":
                changeimg.setBackgroundResource(R.mipmap.txz);
                constellationtime.setText(R.string.tianxietime1);
                constellationtext.setText(R.string.tianxiezuo);
                break;
            case "射手座":
                changeimg.setBackgroundResource(R.mipmap.ssz);
                constellationtext.setText(R.string.sheshouzuo);
                constellationtime.setText(R.string.sheshoutime1);
                break;
            case "摩羯座":
                changeimg.setBackgroundResource(R.mipmap.mjz);
                constellationtext.setText(R.string.mojiezuo);
                constellationtime.setText(R.string.mojietime1);
                break;
        }
    }

    public void gettianqi(String citycode) {
        OkHttpClient client = new OkHttpClient();
        //构造Request对象
        //采用建造者模式，链式调用指明进行Get请求,传入Get的请求地址
        Request request = new Request.Builder().get().url(Url.GETTIANQI + "?citycode=" + citycode).build();
        Call call = client.newCall(request);
        //异步调用并设置回调函数
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, final Response response) {
                try {
                    final String responseStr;
                    responseStr = response.body().string();
                    Message message = new Message();
                    message.obj = responseStr;
                    gettq.sendMessage(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public static TianQiModel userms;
    public Handler gettq = new Handler() {
        public void handleMessage(Message msg) {
            String msgs = null;
            try {
                JSONObject success_Object = null;
                if (msg.obj != null) {
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    msgs = success_Object.getString("msg");
                    if (code.equals("1")) {
                        Gson gson = new Gson();
                        userms = gson.fromJson(msg.obj.toString(),
                                TianQiModel.class);
                        temperature.setText(userms.getData().getWeather().getResults().get(0).getDaily().get(0).getHigh() + "°");
                        address.setText(userms.getData().getWeather().getResults().get(0).getLocation().getName());
                        temperature_text_spacing.setText(userms.getData().getWeather().getResults().get(0).getDaily().get(0).getLow() + "℃~" + userms.getData().getWeather().getResults().get(0).getDaily().get(0).getHigh() + "℃");
                        wind_speed.setText(userms.getData().getWeather().getResults().get(0).getDaily().get(0).getWind_direction() + "风" + userms.getData().getWeather().getResults().get(0).getDaily().get(0).getWind_scale() + "级|湿度:" + userms.getData().getWeather().getResults().get(0).getDaily().get(0).getHumidity() + "%");
                        tomorrow_spacing.setText(userms.getData().getWeather().getResults().get(0).getDaily().get(1).getLow() + "℃~" + userms.getData().getWeather().getResults().get(0).getDaily().get(1).getHigh() + "℃");
                        windlevel.setText(userms.getData().getWeather().getResults().get(0).getDaily().get(1).getWind_direction() + "风" + userms.getData().getWeather().getResults().get(0).getDaily().get(1).getWind_scale() + "级");
                        tomorrows_spacing.setText(userms.getData().getWeather().getResults().get(0).getDaily().get(2).getLow() + "℃~" + userms.getData().getWeather().getResults().get(0).getDaily().get(2).getHigh() + "℃");
                        windlevels.setText(userms.getData().getWeather().getResults().get(0).getDaily().get(2).getWind_direction() + "风" + userms.getData().getWeather().getResults().get(0).getDaily().get(2).getWind_scale() + "级");
                        if (getCurrentTime()) {
                            temperaturetext.setText(userms.getData().getWeather().getResults().get(0).getDaily().get(0).getText_night());
                            state.setText(userms.getData().getWeather().getResults().get(0).getDaily().get(1).getText_night());
                            states.setText(userms.getData().getWeather().getResults().get(0).getDaily().get(2).getText_night());
                        } else {
                            temperaturetext.setText(userms.getData().getWeather().getResults().get(0).getDaily().get(0).getText_day());
                            state.setText(userms.getData().getWeather().getResults().get(0).getDaily().get(1).getText_day());
                            states.setText(userms.getData().getWeather().getResults().get(0).getDaily().get(2).getText_day());
                        }
                    } else
                        Apiutils.SetToast(getActivity(), msgs + "");
                }

            } catch (
                    Exception e) {
                e.printStackTrace();
            }
        }
    };

    public boolean getCurrentTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("HH");
        String hour = sdf.format(new Date());
        int k = Integer.parseInt(hour);
        if ((k >= 0 && k < 6) || (k >= 18 && k < 24)) {
            return true;
        } else {
            return false;
        }
    }

    String time_s;

    public void gettianqi() {
        OkHttpClient client = new OkHttpClient();
        //构造Request对象
        //采用建造者模式，链式调用指明进行Get请求,传入Get的请求地址
        Request request = new Request.Builder().get().url(Url.GETBWL + "?logintoken=" + Url.USER_TOKEN + "&date=" + time_s).build();
        Call call = client.newCall(request);
        //异步调用并设置回调函数
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, final Response response) {
                try {
                    final String responseStr;
                    responseStr = response.body().string();
                    Message message = new Message();
                    message.obj = responseStr;
                    gettqs.sendMessage(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public ArrayList<BWLSModel.data> new_list_views;
    public static BWLSModel userms1;
    public Handler gettqs = new Handler() {
        public void handleMessage(Message msg) {
            String msgs = null;
            try {
                JSONObject success_Object = null;
                if (msg.obj != null) {
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    msgs = success_Object.getString("msg");
                    if (code.equals("1")) {
                        Gson gson = new Gson();
                        new_list_views = new ArrayList<>();
                        userms1 = gson.fromJson(msg.obj.toString(),
                                BWLSModel.class);
                        new_list_views.addAll(userms1.getData());
                        if (new_list_views.size() > 0) {
                            tixing_line.removeAllViews();
                            tixing_line.setVisibility(View.VISIBLE);
                            for (int i = 0; i < new_list_views.size(); i++) {
                                if (new_list_views.get(i).getType().equals("1")) {
                                    LinearLayout relativeLayout = new LinearLayout(getActivity());
                                    TextView textView = new TextView(getActivity());
                                    TextView textViews = new TextView(getActivity());
                                    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                                    LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                                    LinearLayout.LayoutParams lp1s = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                                    lp1.setMargins(20, 24, 0, 24);
                                    lp1s.setMargins(20, 24, 0, 24);
                                    lp.setMargins(0, 2, 0, 0);
                                    relativeLayout.setLayoutParams(lp);
                                    relativeLayout.setOrientation(LinearLayout.HORIZONTAL);
                                    relativeLayout.setBackgroundColor(getActivity().getResources().getColor(R.color.colorwhite));
                                    textView.setLayoutParams(lp1);
                                    long sjc = Long.valueOf(new_list_views.get(i).getRemindtime());
                                    textView.setText(getDateToString(sjc));
                                    textView.setTextColor(getActivity().getResources().getColor(R.color.title_color));
                                    textView.setTextSize(12);
                                    textView.setGravity(Gravity.CENTER);
                                    textViews.setLayoutParams(lp1s);
                                    textViews.setText(new_list_views.get(i).getMemcontent());
                                    textViews.setTextColor(getActivity().getResources().getColor(R.color.text_msg));
                                    textViews.setTextSize(12);
                                    textViews.setGravity(Gravity.CENTER);
                                    relativeLayout.addView(textView);
                                    relativeLayout.addView(textViews);
                                    tixing_line.addView(relativeLayout);
                                }
                            }
                        } else {
                            tixing_line.setVisibility(View.GONE);
                        }
                    } else
                        Apiutils.SetToast(getActivity(), msgs + "");
                }

            } catch (
                    Exception e) {
                e.printStackTrace();
            }

        }

        public String getDateToString(long milSecond) {
            Date date = new Date(milSecond * 1000);
            SimpleDateFormat format = new SimpleDateFormat("MM-dd");
            return format.format(date);
        }
    };

    public void gettianqis(String lat, String lng) {
        OkHttpClient client = new OkHttpClient();
        //构造Request对象
        //采用建造者模式，链式调用指明进行Get请求,传入Get的请求地址
        Request request = new Request.Builder().get().url(Url.GETADDRESS + "?lat=" + lat + "&lng=" + lng).build();
        Call call = client.newCall(request);
        //异步调用并设置回调函数
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, final Response response) {
                try {
                    final String responseStr;
                    responseStr = response.body().string();
                    Message message = new Message();
                    message.obj = responseStr;
                    gethotl.sendMessage(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public static LochtingModel userml;
    public Handler gethotl = new Handler() {
        public void handleMessage(Message msg) {
            String msgs = null;
            try {
                JSONObject success_Object = null;
                if (msg.obj != null) {
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    msgs = success_Object.getString("msg");
                    if (code.equals("1")) {
                        Gson gson = new Gson();
                        userml = gson.fromJson(msg.obj.toString(),
                                LochtingModel.class);
                        Url.address_code = userml.getData().getCode();
                        gettianqi(Url.address_code);
                    } else
                        Apiutils.SetToast(getActivity(), msgs + "");
                }

            } catch (
                    Exception e) {
                e.printStackTrace();
            }
        }
    };

    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

    private void initJsonData() {//解析数据
        String JsonData = new GetJsonDataUtil().getJson(getActivity(), "province.json");//获取assets目录下的json文件数据
        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体
        options1Items = jsonBean;
        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> cityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）
            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String cityName = jsonBean.get(i).getCityList().get(c).getName();
                cityList.add(cityName);//添加城市
                ArrayList<String> city_AreaList = new ArrayList<>();//该城市的所有地区列表
                city_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                province_AreaList.add(city_AreaList);//添加该省所有地区数据
            }
            options2Items.add(cityList);
            options3Items.add(province_AreaList);
        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }

    //  省
    private List<JsonBean> options1Items = new ArrayList<JsonBean>();
    //  市
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    //  区
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();

    private void selectcity() {
        OptionsPickerView pvOptions = new OptionsPickerBuilder(getActivity(), new OnOptionsSelectListener() {
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String opt1tx = options1Items.size() > 0 ?
                        options1Items.get(options1).getPickerViewText() : "";

                String opt2tx = options2Items.size() > 0
                        && options2Items.get(options1).size() > 0 ?
                        options2Items.get(options1).get(options2) : "";

                String opt3tx = options2Items.size() > 0
                        && options3Items.get(options1).size() > 0
                        && options3Items.get(options1).get(options2).size() > 0 ?
                        options3Items.get(options1).get(options2).get(options3) : "";
                String tx = opt2tx + opt3tx;
                Apiutils.getGeoPointBystr(getActivity(), tx);
                gettianqis(Url.latitude, Url.longitude);
            }
        }).setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private boolean isLoaded = false;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    break;
            }
        }
    };
}